package logic

import (
	"context"
	"fmt"
	"login-guard/models/cache"
	"login-guard/models/mysql"

	"login-guard/loginrpc/internal/svc"
	"login-guard/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *loginrpc.RegisterRequest) (*loginrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码不对，请重新输入")
	}
	s, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if s != in.CaptCha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account=?").Find(&user)
	user = mysql.User{
		Account:  in.Account,
		Password: in.Password,
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号已存在请前去登录")
	}
	mysql.DB.Debug().Create(&user)
	return &loginrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
